"""
认证相关路由
"""

from fastapi import APIRouter, HTTPException, Depends, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from typing import Dict, Any
import hashlib
import time
from datetime import datetime, timedelta

from database import get_db
from models.auth import LoginRequest, RefreshTokenRequest, LoginResponse
from models.common import StandardResponse
from models.user import User
from services.auth_service import AuthService
from services.user_service import UserService
from config import get_settings

router = APIRouter(prefix="/auth", tags=["认证"])
security = HTTPBearer()
settings = get_settings()

@router.post("/login", response_model=StandardResponse, summary="用户登录")
async def login(
    request: LoginRequest,
    db: Session = Depends(get_db)
) -> StandardResponse:
    """
    用户登录接口
    
    - **username**: 用户名
    - **password**: 密码
    """
    try:
        # 验证用户
        user_service = UserService(db)
        user = await user_service.authenticate_user(request.username, request.password)
        
        if not user:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail={
                    "code": "LOGIN_FAILED",
                    "type": "authentication_error",
                    "message": "用户名或密码错误",
                    "action": "check_credentials"
                }
            )
        
        # 生成令牌
        auth_service = AuthService()
        access_token = auth_service.create_access_token(
            data={"sub": user.username, "user_id": user.id}
        )
        refresh_token = auth_service.create_refresh_token(user.id)
        
        # 构造响应数据
        login_data = {
            "token": access_token,
            "refreshToken": refresh_token,
            "expiresIn": settings.access_token_expire_minutes * 60,
            "user": {
                "id": user.id,
                "username": user.username,
                "name": user.name,
                "avatar": user.avatar,
                "department": user.department,
                "email": user.email,
                "phone": user.phone
            }
        }
        
        return StandardResponse(
            success=True,
            message="登录成功",
            data=login_data
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"登录失败: {str(e)}"
        )

@router.post("/refresh", response_model=StandardResponse, summary="刷新Token")
async def refresh_token(
    request: RefreshTokenRequest,
    db: Session = Depends(get_db)
) -> StandardResponse:
    """
    刷新访问令牌
    
    - **refreshToken**: 刷新令牌
    """
    try:
        auth_service = AuthService()
        user_service = UserService(db)
        
        # 验证刷新令牌
        user_id = auth_service.verify_refresh_token(request.refresh_token)
        if not user_id:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail={
                    "code": "REFRESH_TOKEN_INVALID",
                    "type": "authentication_error",
                    "message": "刷新令牌无效或已过期",
                    "action": "relogin"
                }
            )
        
        # 获取用户信息
        user = await user_service.get_user_by_id(user_id)
        if not user:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail={
                    "code": "USER_NOT_FOUND",
                    "type": "authentication_error", 
                    "message": "用户不存在",
                    "action": "relogin"
                }
            )
        
        # 生成新的访问令牌
        access_token = auth_service.create_access_token(
            data={"sub": user.username, "user_id": user.id}
        )
        
        return StandardResponse(
            success=True,
            message="Token刷新成功",
            data={
                "token": access_token,
                "expiresIn": settings.access_token_expire_minutes * 60
            }
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Token刷新失败: {str(e)}"
        )

@router.post("/logout", response_model=StandardResponse, summary="用户登出")
async def logout(
    credentials: HTTPAuthorizationCredentials = Depends(security)
) -> StandardResponse:
    """
    用户登出接口
    
    需要在请求头中包含有效的访问令牌
    """
    try:
        # 在实际应用中，这里应该将令牌加入黑名单
        # 或者从Redis中删除相关的会话信息
        
        return StandardResponse(
            success=True,
            message="登出成功"
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"登出失败: {str(e)}"
        )